<template>
  <common-edit-dialog
    title="关联配置"
    :visible="isRelationDialog"
    :info-loading="isRelationLoading"
    @submit="submit"
    @cancel="cancel"
    width="500px"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="form"
      label-width="75px"
      @submit.native.prevent
    >
      <el-form-item label="关联类型" prop="relationType">
        <el-radio-group
          v-model="form.relationType"
          @change="relationTypeChange"
        >
          <el-radio label="T_NONE">不关联</el-radio>
          <el-radio label="T_COMPONENT">关联组件</el-radio>
          <!--          <el-radio label="T_BOARD">看板</el-radio>-->
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="触发字段"
        v-if="form.relationType !== 'T_NONE' && hasTriggerField"
        prop="triggerField"
      >
        <el-select
          v-model="form.triggerField"
          placeholder="请选择"
          filterable
          clearable
        >
          <el-option
            v-for="(field, index) in fieldList"
            :key="index"
            :label="field.label"
            :value="field.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="关联组件"
        v-if="form.relationType === 'T_COMPONENT'"
        prop="componentId"
      >
        <choose-dialog
          @submitDialog="componentChange"
          @clearInfo="componentClear"
          :select-name="form.componentName"
          :select-id="form.componentId"
          :id="id"
        ></choose-dialog>
        <span v-if="isError" style="color: #f56c6c; font-size: 12px"
          >该关联组件已被删除，请重新配置！</span
        >
      </el-form-item>
      <el-form-item
        label="看板"
        v-if="form.relationType === 'T_BOARD'"
        prop="boardId"
      >
      </el-form-item>

      <el-form-item
        label="变量"
        prop="variable"
        v-if="form.relationType !== 'T_NONE'"
      >
        <el-select
          v-model="form.variable"
          placeholder="请选择"
          filterable
          multiple
          clearable
        >
          <el-option
            v-for="item in variableList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="查看方式"
        v-if="form.relationType !== 'T_NONE'"
        prop="relationPreviewMode"
      >
        <el-radio-group v-model="form.relationPreviewMode">
          <el-radio label="M_DIALOG">弹框显示</el-radio>
          <el-radio label="M_TOGGLE">组件切换</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        label="赋值类型"
        prop="assignType"
        v-if="form.relationType !== 'T_NONE'"
      >
        <el-radio-group v-model="form.assignType">
          <el-radio label="A_CATEGORY">类目</el-radio>
          <!-- <el-radio label="A_VALUE">数值</el-radio> -->
        </el-radio-group>
      </el-form-item>
    </el-form>
  </common-edit-dialog>
</template>

<script>
import ChooseDialog from "./chooseDialog";
import { getInfo, getDataSetVariable } from "@/api/screenConfig/dataSet";
import { getComponent } from "@/api/screenConfig/dataComponents";
import { getAssociatedVariable } from "../utils";

export default {
  name: "RelationDialog",
  props: {
    id: {
      type: [String, Number],
    },
    relation: {
      type: Object,
      default: () => ({}),
    },
    fieldList: {
      type: Array,
      default: () => [],
    },
    currentChart: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      isError: false,
      isRelationDialog: false,
      isRelationLoading: false,
      form: {
        relationType: "T_NONE", // T_NONE 不关联 T_COMPONENT 关联组件 T_BOARD 关联看板
        assignType: "A_CATEGORY", // A_CATEGORY 类目 A_VALUE 数值
        componentId: "",
        componentName: "",
        boardId: "",
        boardName: "",
        variable: [],
        triggerField: "", // 触发字段 当前只适用于组件图表类型为表格时
        relationPreviewMode: "M_DIALOG", // M_TOGGLE 组件内部切换 M_DIALOG 弹框打开
      },
      rules: {
        variable: [{ required: true, message: "请选择变量", trigger: "blur" }],
        triggerField: [
          { required: true, message: "请选择触发字段", trigger: "blur" },
        ],
      },
      variableList: [],
    };
  },
  components: {
    ChooseDialog,
  },
  computed: {
    hasTriggerField: function () {
      return ["table-list"].includes(this.currentChart.getInfo().type);
    },
  },
  watch: {
    relation: function () {
      this.initData();
    },
  },
  methods: {
    initData() {
      // 不是表格类型时清除触发字段
      if (this.currentChart === "table-list") {
      } else {
        this.form.triggerField = "";
      }

      Object.keys(this.form).forEach((key) => {
        if (key === "relationType" && !this.relation[key]) {
          this.form[key] = "T_NONE";
        } else if (key === "assignType" && !this.relation[key]) {
          this.form[key] = "A_CATEGORY";
        } else if (key === "relationPreviewMode" && !this.relation[key]) {
          this.form[key] = "M_DIALOG";
        } else {
          this.form[key] = this.relation[key];
        }
      });
      if (this.relation.componentId) {
        this.getComponent(this.relation.componentId);
      }
    },
    submit() {
      if (this.isError) {
      } else {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$emit("change", { ...this.form });
            this.cancel();
          }
        });
      }
    },
    cancel() {
      this.isRelationDialog = false;
    },
    show() {
      this.isRelationDialog = true;
    },
    componentChange(row) {
      this.isError = false;
      this.resetVariable();
      let { id, name, datasetId, chartType } = row ?? {};
      this.form.componentId = id || "";
      this.form.componentName = name || "";
      if (datasetId) this.getVariable(datasetId);
    },
    componentClear() {
      this.isError = false;
      this.resetVariable();
      this.form.componentId = "";
      this.form.componentName = "";
      // this.form.triggerField = ''
      this.variableList = [];
    },
    resetVariable() {
      this.form.variable = [];
    },
    getComponent(id) {
      getComponent({ id })
        .then((res) => {
          if (res.code === 200) {
            console.log("res: ", res.data);
            let { dataset, chartType } = res.data;
            if (dataset && dataset.id) {
              this.getVariable(dataset.id);
            } else {
              console.error("当前组件未关联数据集: ", res);
            }
          } else if (res.code === 511) {
            this.isError = true;
          } else {
            console.error("获取组件信息异常[ 状态码错误 ]: ", res);
          }
        })
        .catch((err) => {
          console.error("获取组件信息异常: ", err);
        });
    },
    getVariable(id) {
      getDataSetVariable({ id: id })
        .then((res) => {
          this.variableList = getAssociatedVariable(res.data).reduce((r, c) => {
            r.push({
              label: c.name,
              value: c.name,
            });
            return r;
          }, []);
        })
        .catch((err) => {
          this.variableList = [];
          console.error("获取数据集详情异常: ", err);
        });
    },
    relationTypeChange() {
      if (this.form.relationType === "T_NONE") {
        this.componentClear();
        this.form.relationPreviewMode = "M_DIALOG";
        this.form.assignType = "A_CATEGORY";
      }
    },
  },
  mounted() {
    this.initData();
  },
};
</script>

<style scoped lang="scss"></style>
